import React, { Component } from 'react';
import { AxiosProvider, Request, Get, Delete, Head, Post, Put, Patch, withAxios } from 'react-axios'
import { Button, Table, Input, Icon, Radio, Modal, Select } from 'antd';
import createHistory from 'history/createHashHistory'
import { Router, Route, Link, Switch } from 'react-router-dom'
import Highlighter from 'react-highlight-words';
import ReactEcharts from 'echarts-for-react';
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const history = createHistory()
const confirm = Modal.confirm;
const Option = Select.Option;
const StockList = withAxios(class StockList extends Component {
    constructor() {
        super();
        this.state = {
            data: "",
            searchText: '',
            sortedInfo: null,
            selectPieColumn: null,
            selectBarColumn: null,
            selectedTable:null
        }
    }
    componentWillMount() {
        

        // this.props.axios('/getCommonTableData').then(result => {

        //     let columnsSource = result.data.columns

        //     this.setState({ data: result.data.data, columnsSource: columnsSource })
        // })
    }

    componentDidMount(){
        let {selectedTable} = this.state
        this.getData(selectedTable)
        
    }

    getData=(selectedTable)=>{
        this.props.axios(`/getCommonTableData?tableName=${selectedTable?selectedTable:'STOCKCODELIST'}`).then(result => {

            let columnsSource = result.data.columns

            this.setState({ data: result.data.data, columnsSource: columnsSource })
        })
    }

    /****search */

    handleSearch = (selectedKeys, confirm) => {
        confirm();
        this.setState({ searchText: selectedKeys[0] });
    }

    handleReset = (clearFilters) => {
        clearFilters();
        this.setState({ searchText: '' });
    }

    getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({
            setSelectedKeys, selectedKeys, confirm, clearFilters,
        }) => (
                <div style={{ padding: 8 }}>
                    <Input
                        ref={node => { this.searchInput = node; }}
                        placeholder={`Search ${dataIndex}`}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
                        style={{ width: 188, marginBottom: 8, display: 'block' }}
                    />
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm)}
                        icon="search"
                        size="small"
                        style={{ width: 90, marginRight: 8 }}
                    >
                        Search
            </Button>
                    <Button
                        onClick={() => this.handleReset(clearFilters)}
                        size="small"
                        style={{ width: 90 }}
                    >
                        Reset
            </Button>
                </div>
            ),
        filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />,
        onFilter: (value, record) => record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
                setTimeout(() => this.searchInput.select());
            }
        },
        render: (text) => (
            <Highlighter
                highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                searchWords={[this.state.searchText]}
                autoEscape
                textToHighlight={text.toString()}
            />
        ),
    })


    /********sort */
    handleChange = (pagination, filters, sorter) => {
        console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            sortedInfo: sorter
        });
    }

    clearFilters = () => {
        this.setState({ filteredInfo: null });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    //pie1
    getOptionPie = () => {
        let { data, selectPieColumn } = this.state
        let pieData = {}
        let pieColumn = []
        for (let i = 0; i < data.length; i++) {
            let singledata = data[i]
            if (pieColumn.includes(singledata[selectPieColumn])) {
                pieData[singledata[selectPieColumn]] = pieData[singledata[selectPieColumn]] + 1
            } else {
                pieColumn.push(singledata[selectPieColumn])
                pieData[singledata[selectPieColumn]] = 1
            }
        }


        let pieSeriesData = []

        for (let key in pieData) {
            let obj = {}
            obj.name = key
            obj.value = pieData[key]
            pieSeriesData.push(obj)
        }
        console.log(66, pieSeriesData.length)
        // var pieSeriesData = [10, 20, 1, 2];
        pieSeriesData.sort(function (a, b) {
            return a.value - b.value;
        })
        // console.log(pieSeriesData); //[1, 2, 10, 20]

        let option = {
            title: {
                text: ' ',
                subtext: '',
                x: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            // legend: {
            //     orient: 'vertical',
            //     left: 'left',
            //     // data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
            //     data: pieColumn
            // },
            series: [
                {
                    name: '饼图',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: pieSeriesData,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        return option;

    }

    onChangeRadioPie = (e) => {
        let { data } = this.state
        let selectPieColumn = e.target.value
        let pieData = {}
        let pieColumn = []
        for (let i = 0; i < data.length; i++) {
            let singledata = data[i]
            if (pieColumn.includes(singledata[selectPieColumn])) {
                pieData[singledata[selectPieColumn]] = pieData[singledata[selectPieColumn]] + 1
            } else {
                pieColumn.push(singledata[selectPieColumn])
                pieData[singledata[selectPieColumn]] = 1
            }
        }


        let pieSeriesData = []

        for (let key in pieData) {
            let obj = {}
            obj.name = key
            obj.value = pieData[key]
            pieSeriesData.push(obj)
        }

        // console.log(66,pieSeriesData.length)
        if (pieSeriesData.length > 500 || pieSeriesData.length == 1) {
            confirm({
                title: 'Confirm',
                content: '选中的数据过多，可能会很卡，确定要展现吗',
                okText: '确认',
                cancelText: '取消',
                onOk: () => { this.setState({ selectPieColumn: e.target.value }) }
                // this.getOptionPie(e.target.value)

            });
        } else {
            this.setState({ selectPieColumn: e.target.value })
        }

        // console.log(`radio checked:${e.target.value}`);


    }

    // bar1
    getOptionBar = () => {
        let { data, selectBarColumn } = this.state
        let pieData = {}
        let pieColumn = []
        for (let i = 0; i < data.length; i++) {
            let singledata = data[i]
            if (pieColumn.includes(singledata[selectBarColumn])) {
                pieData[singledata[selectBarColumn]] = pieData[singledata[selectBarColumn]] + 1
            } else {
                pieColumn.push(singledata[selectBarColumn])
                pieData[singledata[selectBarColumn]] = 1
            }
        }
        // console.log(66,pieData)

        let pieSeriesData = []
        for (let key in pieData) {
            let obj = {}
            obj.name = key
            obj.value = pieData[key]
            pieSeriesData.push(obj)
        }

        // var pieSeriesData = [10, 20, 1, 2];
        pieSeriesData.sort(function (a, b) {
            return a.value - b.value;
        })

        let barColumn = []
        let barValue = []
        for (let key in pieSeriesData) {
            // console.log(88,pieSeriesData[key])
            let obj = pieSeriesData[key]
            barColumn.push(obj.name)
            barValue.push(obj.value)
        }


        let optionBar = {
            title: {
                text: '',
                subtext: ''
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            // legend: {
            //     data: [' ']
            // },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                boundaryGap: [0, 0.01]
            },
            yAxis: {
                type: 'category',
                data: barColumn
            },
            series: [
                {
                    name: ' ',
                    type: 'bar',
                    data: barValue
                }

            ]
        };


        return optionBar;
    }


    onChangeRadioBar = (e) => {
        let { data } = this.state
        let selectBarColumn = e.target.value
        let pieData = {}
        let pieColumn = []
        for (let i = 0; i < data.length; i++) {
            let singledata = data[i]
            if (pieColumn.includes(singledata[selectBarColumn])) {
                pieData[singledata[selectBarColumn]] = pieData[singledata[selectBarColumn]] + 1
            } else {
                pieColumn.push(singledata[selectBarColumn])
                pieData[singledata[selectBarColumn]] = 1
            }
        }


        let pieSeriesData = []

        for (let key in pieData) {
            let obj = {}
            obj.name = key
            obj.value = pieData[key]
            pieSeriesData.push(obj)
        }

        // console.log(66,pieSeriesData.length)
        if (pieSeriesData.length > 500 || pieSeriesData.length == 1) {
            confirm({
                title: 'Confirm',
                content: '选中的数据过多，可能会很卡，确定要展现吗',
                okText: '确认',
                cancelText: '取消',
                onOk: () => { this.setState({ selectBarColumn: e.target.value }) }
                // this.getOptionPie(e.target.value)

            });
        } else {
            this.setState({ selectBarColumn: e.target.value })
        }
    }

    //select
    handleSelectTableChange = (value) => {
        console.log(`selected ${value}`);
        this.getData(value)
        this.setState({selectedTable:value})

    }


    render() {

        // console.log(222, this.state.data)
        let { sortedInfo, filteredInfo, columnsSource, data, selectPieColumn, selectBarColumn,selectedTable } = this.state;

        sortedInfo = sortedInfo || {};
        // console.log(555, selectPieColumn)
        let columns = []
        if (columnsSource != undefined && columnsSource != null) {
            for (let i = 0; i < columnsSource.length; i++) {
                columns.push(
                    {
                        title: columnsSource[i].COMMENTS,
                        dataIndex: columnsSource[i].COLUMN_NAME,
                        key: columnsSource[i].COLUMN_NAME,
                        ...this.getColumnSearchProps(columnsSource[i].COLUMN_NAME),
                        sorter: (a, b) => parseInt(a[columnsSource[i].COLUMN_NAME]).toString() != 'NaN' ?
                            parseInt(a[columnsSource[i].COLUMN_NAME]) - parseInt(b[columnsSource[i].COLUMN_NAME]) :
                            (a[columnsSource[i].COLUMN_NAME].length - b[columnsSource[i].COLUMN_NAME].length),
                        sortOrder: sortedInfo.columnKey === columnsSource[i].COLUMN_NAME && sortedInfo.order,
                    }
                )
            }
        }




        return (
            <div style={{}}>
                <Select defaultValue="lucy" style={{ width: 120 }} onChange={this.handleSelectTableChange}>
                    <Option value="STOCKINFOEVERYDAY">stockinfoeveryday</Option>
                    <Option value="STOCKCODELIST">STOCKCODELIST</Option>
                </Select>
                {columns && <Table key = {selectedTable} dataSource={data} columns={columns} onChange={this.handleChange} />}
                {/* 饼图 */}
                <div >
                    饼图:<RadioGroup size="small" onChange={this.onChangeRadioPie} defaultValue="a" >
                        {columnsSource && columnsSource.map((item) => <RadioButton value={item.COLUMN_NAME}>{item.COMMENTS}</RadioButton>)}
                    </RadioGroup>
                    {selectPieColumn && <ReactEcharts
                        ref={(e) => { this.echartsElement = e }}
                        option={this.getOptionPie()}
                    />}
                    {!selectPieColumn && <p>"图表暂无数据，请点击"</p>}
                </div>

                {/* 柱状图 */}
                <div >
                    柱状图: <RadioGroup size="small" onChange={this.onChangeRadioBar} defaultValue="a" >
                        {columnsSource && columnsSource.map((item) => <RadioButton value={item.COLUMN_NAME}>{item.COMMENTS}</RadioButton>)}
                    </RadioGroup>
                    {selectBarColumn && <ReactEcharts
                        ref={(e) => { this.echartsElement = e }}
                        option={this.getOptionBar()}
                    />}
                    {!selectBarColumn && <p>"图表暂无数据，请点击"</p>}
                </div>

            </div>
        )
    }
})
export default StockList;